Executing code dynamically is security-sensitive. It has led in the past to the following vulnerabilities:
Some APIs enable the execution of dynamic code by providing it as strings at runtime. These APIs might be useful in some very specific
meta-programming use-cases. However most of the time their use is frowned upon as they also increase the risk of Injected Code. Such attacks can either run on the server or in the client (exemple:
XSS attack) and have a huge impact on an application’s security.
This rule raises issues on calls to eval
and Function
constructor. This rule does not detect code injections. It only
highlights the use of APIs which should be used sparingly and very carefully. The goal is to guide security code reviews.
The rule also flags string literals starting with javascript:
as the code passed in javascript:
URLs is evaluated the
same way as calls to eval
or Function
constructor.
Ask Yourself Whether
- the executed code may come from an untrusted source and hasn’t been sanitized.
- you really need to run code dynamically.
There is a risk if you answered yes to any of those questions.
Recommended Secure Coding Practices
Regarding the execution of unknown code, the best solution is to not run code provided by an untrusted source. If you really need to do it, run the
code in a sandboxed environment. Use jails, firewalls and whatever means your
operating system and programming language provide (example: Security Managers in java, iframes and same-origin
policy for javascript in a web browser).
Do not try to create a blacklist of dangerous code. It is impossible to cover all attacks that way.
Avoid using dynamic code APIs whenever possible. Hard-coded code is always safer.
Sensitive Code Example
let value = eval('obj.' + propName); // Sensitive
let func = Function('obj' + propName); // Sensitive
location.href = 'javascript:void(0)'; // Sensitive
Exceptions
This rule will not raise an issue when the argument of the eval
or Function
is a literal string as it is reasonably
safe.
See